package com.edu.service.impl;

import com.edu.domin.dto.ArticleDTO;

import com.edu.domin.vo.ArticleVo;
import com.edu.domin.vo.CommentVo;
import com.edu.entity.Article;
import com.edu.entity.Comment;
import com.edu.entity.User;
import com.edu.entity.UserInfo;
import com.edu.mapper.ArticleMapper;
import com.edu.service.IArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.service.ICommentService;
import com.edu.service.IUserInfoService;
import com.edu.service.IUserService;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户文章表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-15
 */
@Service
@Slf4j
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {
@Autowired
private IUserService userService;
@Autowired
private ICommentService commentService;
@Autowired
private IUserInfoService userInfoService;
    @Override
    public List<ArticleVo> listeryone() {
        //筛选合格的文章，根据时间排序
        List<Article> list = query()
                .eq("is_approved", 2)
                .orderByDesc("view_count")
                .list();
        List<ArticleVo> listvo = new ArrayList<>();
        //封装数据，添加一个字段Username
        for(Article article : list){
            ArticleVo vo = new ArticleVo();
            BeanUtils.copyProperties(article, vo);
            User user = userService.getById(article.getUserId());
            vo.setUsername(user.getUsername());
            listvo.add(vo);
        }
        return listvo;
    }

    @Override
    public void updatearticle(ArticleDTO articleDTO, Long id) {
        Article article = new Article();
        BeanUtils.copyProperties(articleDTO, article);
        article.setUserId(Math.toIntExact(id));
        updateById(article);
        log.info("更新文章成功: {}", article);
    }

    @Override
    public void savearticle(ArticleDTO articleDTO, Long id) {
        Article article = new Article();
        BeanUtils.copyProperties(articleDTO, article);
        article.setUserId(Math.toIntExact(id));
        save(article);
        log.info("保存文章成功: {}", article);
    }

    @Override
    public ArticleVo getVoById(Long id) {
        //查询文章详情
        Article article = getById(id);
        update().eq("id", id).set("view_count", article.getViewCount() + 1).update(article);
        //添加用户信息·
        ArticleVo vo = new ArticleVo();
        BeanUtils.copyProperties(article, vo);
        //用户信息
        User user1 = userService.getById(article.getUserId());
        //用户头像
        UserInfo userInfo = userInfoService.query().eq("user_id", user1.getId()).one();
        if (user1 != null && userInfo != null ) {
           vo.setUsername(user1.getUsername());
           vo.setImage(userInfo.getImage());
        }
        //查询评论表信息
        List<Comment> comments = commentService.query().eq("article_id", id).list();
        //提取评论信息中的用户信息
        List<Long> userIdlist = comments.stream()
                .map(Comment::getUserId)
                .collect(Collectors.toList());
        //如果userIdlist为空，则返回空集合
        List<User> users = new ArrayList<>();
        if (!userIdlist.isEmpty()) {
             users = userService.listByIds(userIdlist);
        }
        // 构建 userId -> User 的 Map，便于快速查找
        Map<Long, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        List<CommentVo> list = new ArrayList<>();

        //封装评论信息,添加一个字段Username
       for (Comment comment : comments){
           CommentVo vo1 = new CommentVo();
           BeanUtils.copyProperties(comment,vo1);
           //封装一个name进去

           // 从 map 中取出对应用户
           User user = userMap.get(comment.getUserId());
           if (user != null) {
               vo1.setUsername(user.getUsername());
           } else {
               vo1.setUsername("未知用户");
           }
          list.add(vo1);
       }
       vo.setList(list);
        return vo;
    }

    @Override
    public List<ArticleVo> querylist() {
        //筛选是否合格的文章，根据更新时间排序
        List<Article> list = query()
                .eq("is_approved", 1)
                .orderByDesc("updated_at")
                .list();

        //封装数据，添加一个字段Username
        List<ArticleVo> listvo = new ArrayList<>();
        for(Article article : list){
            ArticleVo vo = new ArticleVo();
            BeanUtils.copyProperties(article, vo);
            User user = userService.getById(article.getUserId());
            vo.setUsername(user.getUsername());
            listvo.add(vo);
        }
        return listvo;
    }

    @Override
    public List<ArticleVo> listeryByid(Long id) {
        //筛选合格的和分类文章，根据时间排序,
        List<Article> list = query()
                .eq("is_approved", 2)
                .eq("category_id",  id)
                .orderByDesc("view_count")
                .list();
        List<ArticleVo> listvo = new ArrayList<>();
        //封装数据，添加一个字段Username
        for(Article article : list){
            ArticleVo vo = new ArticleVo();
            BeanUtils.copyProperties(article, vo);
            User user = userService.getById(article.getUserId());
            vo.setUsername(user.getUsername());
            listvo.add(vo);
        }
        return listvo;
    }


}
